﻿using System;
using System.Timers;

using OptimalisationFramework.Interfaces;
using OptimalisationFramework.Utilities;

namespace OptimalisationFramework.Metaheuritics
{
    class IterativeLocalSearch : AbstractTimer,IMetaHeuristic
    {
        private ITrajectorySearch sol;

        // threaded lock situation
        private object locker;

        public IterativeLocalSearch(ITrajectorySearch sol, uint seconds)
        {
            this.sol = sol;
            locker = new object();
            SetTime(seconds);
        }


        public ITrajectorySearch GetSolution()
        {
            return sol;
        }

        public void Start()
        {
            if (tm != null)
            {
                StartTimer();
            }
            Solve();
        }

        public void Stop()
        {
            stopProcess = true;
        }

        public void Solve()
        {
            ITrajectorySearch min = sol;
            sol = sol.GenerateInitialSolution();
            while (!sol.StopSearch() && !stopProcess)
            {
                lock (locker)
                {
                    sol = sol.AdjustSolution();
                    if (sol.ObjectifFunction() < min.ObjectifFunction())
                    {
                        min = sol;
                    }
                }
            }
            if (tm != null)
            {
                StopTimer();
            }
        }        
    }
}
